package pro.cherish.helloworld.server;

import io.netty.channel.*;
import lombok.extern.slf4j.Slf4j;

import java.net.InetAddress;

/**
 * @author 创建人：lys
 * @version 版本号：V1.0
 * <p>
 * ***************************修订记录************************************
 * 2020-6-15 lys 创建该类功能。
 * **********************************************************************
 * </p>
 * @ClassName 类名：ServerHandler
 * @Description 功能说明：
 * <p>
 * TODO
 * </p>
 * **********************************************************************
 * @date 创建日期： 2020-6-15 
 */
@ChannelHandler.Sharable
@Slf4j
public class ServerHandler extends SimpleChannelInboundHandler<String> {
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		log.info("pro.cherish.helloworld.server.ServerHandler.channelActive");
		String hostName = InetAddress.getLocalHost().getHostName();
		ctx.write("welcome to " + hostName);
		super.channelActive(ctx);
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		log.info("pro.cherish.helloworld.server.ServerHandler.channelReadComplete");
		super.channelReadComplete(ctx);
	}

	@Override
	protected void channelRead0(ChannelHandlerContext channelHandlerContext, String request) throws Exception {
		log.info("pro.cherish.helloworld.server.ServerHandler.channelRead0");
		log.info("读取消息={}", request);
		String response;
		boolean close = false;
		if (request.isEmpty()) {
			response = "Please type something.\r\n";
		} else if ("bye".equals(request.toLowerCase())) {
			response = "Have a good day!\r\n";
			close = true;
		} else {
			response = "Did you say '" + request + "'?\r\n";
		}
		ChannelFuture channelFuture = channelHandlerContext.writeAndFlush(response);
		if (close) {
			channelFuture.addListener(ChannelFutureListener.CLOSE);
		}
	}
}
